/** Copyright 2020 Zhejiang Lab and Zhejiang University. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================
*/


import { ROOT_URL } from '../config'
import * as d3 from "d3"
import axios from 'axios'

export const parseTime = function (time) {
    if (time == null) {
        return "--";
    }
    const d = new Date(time);
    const local_time = d.toLocaleString("zh-Hans-CN", { hour12: false });
    return local_time.replace(' 24', ' 00');
}

export const addSelectField = function (obj) {
    obj.selected = false
    return obj
}

export const downloadJson = function (url, prefix = ROOT_URL) {
    if (prefix) {
        url = `${prefix}/${url}`;
    }
  
    axios.get(url).then(res => {
        var result = JSON.stringify(res);
        var datastr = `data:text/json;charset=utf-8,${result}`;
        var downloadAnchorNode = document.createElement("a");
        downloadAnchorNode.setAttribute("href", datastr);
        downloadAnchorNode.setAttribute("download", url.split('/').pop());
        downloadAnchorNode.click();
        downloadAnchorNode.remove();
    })
}

export const download = function (url, prefix = ROOT_URL) {
    if (prefix) {
        window.open(`${prefix}/${url}`);
    }
    else {
        window.open(url);
    }
}

export const setIsDialogOpen = function (state, is_dialog_open) {
    state.is_dialog_open = is_dialog_open
}

export const setDialogContent = function (state, dialog_content) {
    state.dialog_content = dialog_content
}

export const closeDialog = function (event) {
    console.log(event);
    this.setIsDialogOpen(false);
    this.setDialogContent("");
}

export const setIsUpdateDialogOpen = function (state, is_update_dialog_open) {
    state.is_update_dialog_open = is_update_dialog_open
}

export const closeUpdateDialog = function (event) {
    console.log(event);
    this.setIsUpdateDialogOpen(false);
}

export const setIsLoading = function(state, is_loading) {
    state.is_loading = is_loading
}

export const shareData = function ({ commit, state }, { file_id, file_type, is_public }) {
    console.log('share data', file_id, file_type)
    let url;
    if (file_type == "m") {
        url = `${ROOT_URL}/api/model/share_link`
    }
    else if (file_type == "d") {
        url = `${ROOT_URL}/api/dataset/share_link`
    }
    else {
        commit("setIsDialogOpen", true)
        commit('setDialogContent', "错误的数据类型")
        return
    }
    if (is_public) {
        commit("setIsDialogOpen", true)
        commit('setDialogContent', "已公开，不需分享")
    }
    else {
        axios.post(url, {
            file_id: file_id,
            file_type: file_type,
            duration: 7,
        })
            .then((response) => {
                const url = `${window.origin}/#/share/${file_type}/${response.data}`
                console.log('share success', response.data)
                commit("setIsDialogOpen", true)
                commit('setDialogContent', url)
            })
            .catch((errors) => {
                commit('setErrors', errors)
                commit("setIsDialogOpen", true)
                commit('setDialogContent', "分享失败")
            })
    }
}

export const getPrivilege = function ({ commit, state }, { file_type, share_link }) {
    console.log("getPrivilege", share_link, file_type)
    let url;
    if (file_type == "m") {
        url = `${ROOT_URL}/api/model/share_model`
    }
    else if (file_type == "d") {
        url = `${ROOT_URL}/api/dataset/share_dataset`
    }
    else {
        commit("setIsDialogOpen", true)
        commit('setDialogContent', "错误的数据类型")
        return
    }

    axios.post(url, {
        share_link: share_link,
    })
        .then((response) => {
            console.log('get privilege success', response.data)
            commit("setIsDialogOpen", true)
            commit('setDialogContent', "权限获取成功")
        })
        .catch((errors) => {
            console.log("errors", errors)
            commit('setErrors', errors)
            commit("setIsDialogOpen", true)
            commit('setDialogContent', `权限获取失败：${errors.response.data}`)
        })
}

export const hasDuplicates = function (array) {
    return (new Set(array)).size !== array.length;
}

export const convertArray2String = function (accumulator, currentValue) {
    return accumulator + ', ' + currentValue
}

export const openDetailPage = function (task_id) {
    let routeData = this.$router.resolve({ name: "Task Detail", params: { task_id: task_id } });
    window.open(routeData.href, '_blank');
    // this.$router.push({name: "Task Detail", params: {task_id: task_id}})
}

const _bisect_x = d3.bisector(d => d[1]).left;

export const bisect = function (data, x) {
    const index = _bisect_x(data, x, 1);

    if (index == data.length) {
        return data[index - 1]
    }
    const a = data[index - 1];
    const b = data[index];

    return x - a[1] > b[1] - x ? b : a;
}

export const drawToolTip = function (g, value) {
    if (!value) return g.attr("display", "none");

    g.attr("display", null);

    //   keep one element
    const path = g
        .selectAll("path")
        .data([null])
        .join("path")
        .attr("fill", "white")
        .attr("stroke", "black");

    const text = g
        .selectAll("text")
        .data([null])
        .join("text")
        .call(text =>
            text
                .selectAll("tspan")
                .data((value + "").split(/\n/))
                .join("tspan")
                .attr("x", 0)
                .attr("y", (d, i) => `${i * 1.2}em`)
                .style("font-weight", (_, i) => (i ? null : "light"))
                .text(d => d)
        );

    const { tx, ty, width: tw, height: th } = text.node().getBBox();

    text.attr("transform", `translate(5,15)`);
    path.attr("d", `M0,0H${tw + 10}v${th + 10}H0z`);
}

export const getValidHTMLID = function(id) {
    return id.replace(/[^a-zA-Z0-9_\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}]/gu, '')
}